package com.irate.activity;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.irate.dao.UserDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.provider.ContentManager;
import com.irate.provider.SessionLogin;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;

public class LoginActivity extends Activity {

	protected ImageView login_back_button;
	protected ImageView login_forward_button;
	protected EditText txt_email;
	protected EditText txt_password;
	protected TextView txt_forgot_pass;

	protected ProgressDialog dialog;

	protected ImageView imageBg;
	protected UserDAO userDAO;

	protected SessionLogin session;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		init();
		execute();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		startActivityForResult(new Intent(this, WelcomeActivity.class), 1);
	}

	private void init() {
		session = new SessionLogin(this);

		txt_forgot_pass = (TextView) findViewById(R.id.forgot_your_pass);

		login_back_button = (ImageView) findViewById(R.id.login_back_button);

		login_forward_button = (ImageView) findViewById(R.id.login_forward_button);
		imageBg = (ImageView) findViewById(R.id.login_background);
		txt_email = (EditText) findViewById(R.id.email);
		txt_password = (EditText) findViewById(R.id.password);

		userDAO = new UserDAO();
	}

	private void execute() {

		txt_forgot_pass.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (txt_email.getText().toString().equals("")) {
					Toast.makeText(
							LoginActivity.this,
							getResources().getString(R.string.invalid_username),
							Toast.LENGTH_SHORT).show();
				} else {
					dialog = ProgressDialog.show(LoginActivity.this,
							getResources().getString(R.string.forgot_pass),
							getResources().getString(R.string.loading), true);

					userDAO.forgorPass(txt_email.getText().toString(),
							handlerForgotPass, LoginActivity.this, dialog);
				}
			}
		});

		String[] loginData = session.getLoginSession();
		if (!loginData[0].equals("") && !loginData[1].equals("")) {
			// userDAO.login(loginData[0], loginData[1], handler, this, dialog);
			txt_email.setText(loginData[0]);
			txt_password.setText(loginData[1]);
		}

		txt_email.requestFocus();

		txt_email.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!txt_password.getText().toString().equals(""))
					txt_password.setText("");

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		login_back_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		login_forward_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//
				// SimpleFacebook sf = SimpleFacebook.getInstance();
				// if (sf.isLogin()) {
				// sf.logout(new OnLogoutListener() {
				//
				// @Override
				// public void onFail(String reason) {
				//
				// }
				//
				// @Override
				// public void onException(Throwable throwable) {
				//
				// }
				//
				// @Override
				// public void onThinking() {
				//
				// }
				//
				// @Override
				// public void onLogout() {
				//
				// }
				// });
				// }

				if (txt_email.getText().toString().trim().equals("")
						&& txt_password.getText().toString().trim().equals("")) {
					Toast.makeText(
							LoginActivity.this,
							getResources().getString(R.string.invalid_username)
									+ ", "
									+ getResources().getString(
											R.string.invalid_password),
							Toast.LENGTH_SHORT).show();
				} else {
					if (txt_email.getText().toString().trim().equals("")) {
						Toast.makeText(
								LoginActivity.this,
								getResources().getString(
										R.string.invalid_username),
								Toast.LENGTH_SHORT).show();
					} else {
						if (txt_password.getText().toString().trim().equals("")) {
							Toast.makeText(
									LoginActivity.this,
									getResources().getString(
											R.string.invalid_password),
									Toast.LENGTH_SHORT).show();
						} else {
							dialog = ProgressDialog.show(LoginActivity.this,
									getResources().getString(R.string.login),
									getResources().getString(R.string.loading),
									true);
							userDAO.login(
									txt_email.getText().toString().trim(),
									txt_password.getText().toString().trim(),
									handler, LoginActivity.this, dialog);
						}

					}
				}

			}
		});

		setWidthBackground();
	}

	private void setWidthBackground() {
		Display display = getWindowManager().getDefaultDisplay();
		@SuppressWarnings("deprecation")
		int width = display.getWidth();

		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				width * 80 / 100, width * 80 / 100);
		imageBg.setLayoutParams(lp);
	}

	AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			userDAO.parsedata(new String(response));

			if (ContentManager.getInstance().isLogin()) {
				session.createLoginSession(txt_email.getText().toString()
						.trim(), txt_password.getText().toString().trim());
				session.setLoginState(true);
				startActivity(new Intent(LoginActivity.this, MainActivity.class));
				finish();
			} else {
				Toast.makeText(LoginActivity.this,
						getResources().getString(R.string.login_error),
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(LoginActivity.this,
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};

	AsyncHttpResponseHandler handlerForgotPass = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(LoginActivity.this,
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			Toast.makeText(LoginActivity.this,
					getResources().getString(R.string.forgot_fail),
					Toast.LENGTH_SHORT).show();
		}
	};

}
